package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/GetPayment/{id}")
    public CommonResult<Payment> GetPayment(@PathVariable("id") Long id){
        log.info("id{}:"+id);
        Payment payment = paymentService.selectById(id);
        return new CommonResult(200,"查询成功："+"\t 端口号为：" + serverPort,payment);
    }

    @PostMapping("/CreatePayment")
    public CommonResult<Payment> CreatePayment(@RequestBody Payment payment){
        int result = paymentService.insertPayment(payment);
        return new CommonResult(200,"插入成功：" + result,null);
    }

    @GetMapping(value = "/discovery")
    public Object discovery()
    {
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
                    + element.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("Timeout")
    public String Timeout(){
        int time = 3;
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "访问成功，访问时间：" + time;
    }

    /**
     * 测试gateWay网关
     * @return
     */
    @GetMapping("/get")
    public String PaymenGet(){

        return serverPort;
    }

    @GetMapping("/lb")
    public String PaymenLb(){

        return serverPort;
    }

}
